
## see https://asjadnaqvi.github.io/DiD/docs/code_r/07_did_multiplegt_r/

rm(list = ls())
library(tidyverse)
library(readstata13)
library(DIDmultiplegt)
library(broom)

here::here()

# Read state-level data
d <- as_tibble(read.dta13("data-state-level.dta"))

mod_dCDH20 = did_multiplegt(
  d, 'count', 'statecode', 'year', 'jointopsyeardummy', # original regression params
  dynamic   = 7,                  # no. of post-treatment periods
  placebo   = 10,                  # no. of pre-treatment periods
  brep      = 20,                  # no. of bootstraps (required for SEs)
  cluster   = 'statecode'               # variable to cluster SEs on
)

# Create a tidier for "multiplegt" objects
tidy.did_multiplegt = function(x, level = 0.95) {
ests = x[grepl("^placebo_|^effect|^dynamic_", names(x))]
ret = data.frame(
term      = names(ests),
estimate  = as.numeric(ests),
std.error = as.numeric(x[grepl("^se_placebo|^se_effect|^se_dynamic", names(x))]),
N         = as.numeric(x[grepl("^N_placebo|^N_effect|^N_dynamic", names(x))])
) |>
# For CIs we'll assume standard normal distribution
within({
conf.low  = estimate - std.error*(qnorm(1-(1-level)/2))
conf.high = estimate + std.error*(qnorm(1-(1-level)/2))
})
return(ret)
}

tidy.did_multiplegt(mod_dCDH20)
tidy_dCDH20 = tidy.did_multiplegt(mod_dCDH20)

# install.packages("ggplot2")
library(ggplot2)
theme_set(theme_minimal(base_family = "ArialNarrow")) # Optional

tidy_dCDH20 |>
  within({
    term = gsub("^placebo_", "-", term)
    term = gsub("^effect", "0", term)
    term = gsub("^dynamic_", "", term)
    term = as.integer(term)
  }) |>
  ggplot(aes(x = term, y = estimate, ymin = conf.low, ymax = conf.high)) +
  geom_pointrange() +
  theme_bw() +
  labs(
    x = "Time to treatment", y = "Effect size"
  ) + 
  geom_hline(yintercept = 0) + 
  geom_point(size=6) +
  geom_errorbar(size=2, width=0) +
  theme(text = element_text(size = 35)) +
  scale_x_continuous(breaks = -10:7)

ggsave("Figure VI.I.jpg", 
       height = 12, width = 9 * 2.5)
